package servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.annotation.Resource;
import javax.ejb.EJB;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceUnit;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.transaction.UserTransaction;

import model.Myuser;
import model.Tag;
import model.Target;

import ejb.LikeFacadeEJBRemote;
import ejb.TagFacadeEJBRemote;
import ejb.TargetFacadeEJBRemote;
import ejb.UserFacadeEJBRemote;

@WebServlet("/TagServlet")
public class TagServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	@PersistenceUnit
	EntityManagerFactory emf;

    @Resource private UserTransaction utx; 

	@PersistenceContext
	EntityManager em;
	
    @EJB LikeFacadeEJBRemote lf; 
    @EJB TargetFacadeEJBRemote targetf;
    @EJB UserFacadeEJBRemote uf;
    @EJB TagFacadeEJBRemote tf;
	
    public TagServlet() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		HttpSession session=request.getSession();
		
		String tag = (String)request.getParameter("tag");
		String targetid = (String)request.getParameter("targetid");
		int tid = Integer.parseInt(targetid);

		response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
		out.print("<html><body>");
		
		try{
			utx.begin();
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}
			
		{
			
		Target target = new Target();
		target= targetf.queryByTargetID(tid);
		String username = (String)session.getAttribute("username");
		Myuser u = new Myuser();
		u= uf.findUserByName(username);
				
		//tag not exist
		if(tf.ifTagExist(tag)==false){
			//create tag
			tf.createTag(tag);
			Tag justAddedTag = tf.queryTagByName(tag);
			
			if(tf.ifTargetTagExist(target, justAddedTag)==false){
				tf.createTargetTag(u, target, justAddedTag);
			}
			
			boolean l = lf.ifLikeExist(u, target);
			String liked = "";
			if(l==true){
				liked = "true";
			}else{
				liked = "false";
			}
			
			List<Tag> tag_list = tf.getTagListByTarget(target);
			request.setAttribute("taglist", tag_list);
			request.setAttribute("liked", liked);
			request.setAttribute("return_t", target);
            request.getRequestDispatcher("Target.jsp").forward(request, response);
		}
		// tag already exist
		else{
			Tag existTag = tf.queryTagByName(tag);
			
			//targetTag already exist in the target
			if(tf.ifTargetTagExist(target, existTag)==true){
				
				boolean l = lf.ifLikeExist(u, target);
				String liked = "";
				if(l==true){
					liked = "true";
				}else{
					liked = "false";
				}
				
				List<Tag> tag_list = tf.getTagListByTarget(target);
				request.setAttribute("taglist", tag_list);
				request.setAttribute("liked", liked);
				request.setAttribute("return_t", target);
	            request.getRequestDispatcher("Target.jsp").forward(request, response);
			}
			//targetTag not exist but tag exist
			else{
				
				Tag hasTag = tf.queryTagByName(tag);
				tf.createTargetTag(u, target, hasTag);
				
				boolean l = lf.ifLikeExist(u, target);
				String liked = "";
				if(l==true){
					liked = "true";
				}else{
					liked = "false";
				}
				
				List<Tag> tag_list = tf.getTagListByTarget(target);
				request.setAttribute("taglist", tag_list);
				request.setAttribute("liked", liked);
				request.setAttribute("return_t", target);
	            request.getRequestDispatcher("Target.jsp").forward(request, response);

			}
		}
		
		
		}
		
		try{
			utx.commit();
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		
		}
	
	}

	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}
